package com.dayuanit.dy15.atm.service.impl;

import com.dayuanit.dy15.atm.entity.User;
import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.mapper.UserMapper;
import com.dayuanit.dy15.atm.service.UserService;
import com.dayuanit.dy15.atm.util.DBUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;

public class UserServiceImpl implements UserService {
    @Override
    public User login(String username, String password) {
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            throw new BizException("有必填参数为空");
        }

        // 用户存在吗？ 密码对吗？
        try (SqlSession sqlSession = DBUtils.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.getUserByName(username);
            if (null == user) {
                throw new BizException("用户名不存在或者密码错误");
            }

            if (!user.getPassword().equals(password)) {
                throw new BizException("用户名不存在或者密码错误");
            }

            return user;
        }
    }

    @Override
    public void register(String username, String password, String confirmPassword) {
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password) ||
                StringUtils.isBlank(confirmPassword)) {
            //国际化的配置文件
            throw new BizException("有必填参数为空");
        }

        if (!confirmPassword.equals(password)) {
            throw new BizException("两次密码不相等");
        }

        //TODO 判断用户名是否存在
        try (SqlSession sqlSession = DBUtils.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.getUserByName(username);
            if (null != user) {
                throw new BizException("用户名已存在");
            }

            user = new User();
            user.setCreateTime(new Date());
            user.setPassword(password);
            user.setUsername(username);

            int rows = userMapper.insert(user);
            if (1 != rows) {
                throw new BizException("注册失败");
            }
        }
    }
}
